package com.example.demo.offer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Offer07 {
    public static void main(String[] args) {
        int[] nums = new int[]{-1,0,1,2,-1,-4};
        System.out.println(threeSum(nums));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        int length = nums.length;
        for (int first = 0; first < length; first++) {
            //不需要重复的
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int third = length - 1;
            int target = -nums[first];
            for (int second = first + 1; second < length; second++) {
                if (second > first+1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while (second < third && nums[third] + nums[second] > target) {
                    third--;
                }
                if(second == third){
                    break;
                }
                if(nums[third] + nums[second] == target){
                    List<Integer> ans = new ArrayList<>();
                    ans.add(nums[first]);
                    ans.add(nums[second]);
                    ans.add(nums[third]);
                    res.add(ans);
                }
            }
        }
        return res;
    }
}
